package com.jrx.anytxn.transaction.job.marketingFile.config;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.utils.TargzUtil;
import com.jrx.anytxn.transaction.config.InterestFileConfig;
import com.jrx.anytxn.transaction.config.MarketingFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.job.marketingFile.step.MergeMarketingFileListener;
import com.jrx.anytxn.transaction.service.IMarketingFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableConfigurationProperties(InterestFileConfig.class)
public class MergeMarketingFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MergeMarketingFileConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private MarketingFileConfig marketingFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IMarketingFileService marketingFileService;
    @Autowired
    private MergeMarketingFileListener mergeMarketingFileListener;

    @Bean
    public Job mergeMarketingFileJob(){
        return jobBuilderFactory.get("mergeMarketingFileJob").incrementer(new RunIdIncrementer()).listener(mergeMarketingFileListener)
                .start(mergeMarketingSumFileStep())  //合并营销汇总文件
                .next(mergeMarketingDetailFileStep())//合并营销明细文件
                .next(generateMarketSignFileStep())  //生成验签文件
                .build();
    }

    @Bean
    public Step mergeMarketingSumFileStep() {
        return stepBuilderFactory.get("mergeMarketingSumFileStep")
                .tasklet(mergeMarketingSumFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeMarketingSumFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("营销汇总文件合并开始。。。。。。");
            String filePath = marketingFileConfig.getMarketingFilePath();
            String fileName = marketingFileConfig.getMarketingFileName();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            marketingFileService.mergeFile(org, filePath, fileName, TransBizConstant.FILE_NAME_MARKET_SUM);

            logger.debug("营销汇总文件合并处理完成");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step mergeMarketingDetailFileStep() {
        return stepBuilderFactory.get("mergeMarketingDetailFileStep")
                .tasklet(mergeMarketingDetailFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeMarketingDetailFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("营销明细文件合并开始。。。。。。");
            String filePath = marketingFileConfig.getMarketingFilePath();
            String fileName = marketingFileConfig.getMarketingFileName();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            marketingFileService.mergeFile(org, filePath, fileName, TransBizConstant.FILE_NAME_MARKET_DET);

            logger.debug("营销明细文件合并处理完成");
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public Step generateMarketSignFileStep() {
        return stepBuilderFactory.get("generateMarketSignFileStep")
                .tasklet(generateMarketSignFileTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet generateMarketSignFileTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("营销验签文件生成开始。。。。。。");
            String filePath = marketingFileConfig.getMarketingFilePath();

            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String toDay = DateUtils.format(org.getToday(),DateUtils.DATE_PATTERN_ANOTHER);
            //拼接/租户/日期 路径
            String reportingPath = filePath + org.getTenantId() + File.separator + toDay + File.separator;
            String outPath = marketingFileConfig.getOutDir();

            String marketSumFileName = org.getTenantId() + "_" + TransBizConstant.FILE_NAME_MARKET_SUM + "_" + "ADD" + "_" + toDay;
            String marketSumFilePath = reportingPath + marketSumFileName + ".del";

            String marketDetFileName = org.getTenantId() + "_" + TransBizConstant.FILE_NAME_MARKET_DET + "_" + "ADD" + "_" + toDay;
            String marketDetFilePath = reportingPath + marketDetFileName  + ".del";

            String signFilePath = reportingPath + "indicate.txt";
            String tarFilePath = reportingPath + outPath + toDay + "_" + org.getTenantId() + ".tar";
            String okFilePath = reportingPath + outPath + toDay + "_" + org.getTenantId() + ".ok";
            //生成验签文件
            List<File> marketFileList = new ArrayList<>();
            if(marketingFileService.generatSignFile(org, marketSumFilePath, marketSumFileName, signFilePath)){
                marketFileList.add(new File(marketSumFilePath));
                logger.info("汇总文件的验签文件写入成功");
            }

            if(marketingFileService.generatSignFile(org, marketDetFilePath, marketDetFileName, signFilePath)){
                marketFileList.add(new File(marketDetFilePath));
                logger.info("明细文件的验签文件写入成功");
            }

            marketFileList.add(new File(signFilePath));
            File targetFile = new File(tarFilePath);
            //将营销及验签文件进行打包
            TargzUtil.pack(marketFileList, targetFile);
            //打包成功，生成OK文件
            if(targetFile.exists()){
                File okFile = new File(okFilePath);
                try (FileWriter fw = new FileWriter(okFile);
                    BufferedWriter writer = new BufferedWriter(fw) ){
                    writer.write("");
                    writer.flush();
                } catch (IOException e) {
                    logger.error("生成OK文件失败");
                    throw new RuntimeException(e);
                }
            }

            logger.debug("营销验签文件生成处理完成");
            return RepeatStatus.FINISHED;
        };
    }
}
